package com.ruicar.afs.cloud.admin.util;

import com.ruicar.afs.cloud.admin.enums.PassWordBaseRule;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class PassValidateUtil {
    private static final Map<String,PassWordBaseRule> passWordBaseRuleMap = new HashMap<>();
    static {
        passWordBaseRuleMap.putAll(Arrays.stream(PassWordBaseRule.values()).collect(Collectors.toMap(PassWordBaseRule::getCode,Function.identity())));
    }
    public static void validatePass(String configureLevel,long minLength ,long maxLength,String passWord){
        Assert.isTrue(StringUtils.isNotEmpty(passWord),"密码不能为空");
        Assert.isTrue(!(passWord.length()>maxLength||passWord.length()<minLength), MessageFormat.format("密码长度必须在[{0},{1}]间",minLength,maxLength));
        if(StringUtils.isNotEmpty(configureLevel)&&Arrays.stream(configureLevel.split(",")).filter(str->str.equalsIgnoreCase(PassWordBaseRule.ANY.getCode())).count()==0){
            List<String> stringList = Arrays.stream(configureLevel.split(",")).filter(str->!str.equalsIgnoreCase(PassWordBaseRule.ANY.getCode())).collect(Collectors.toList());
            for (String rule : stringList) {
                Assert.isTrue(passWordBaseRuleMap.get(rule).getPattern().matcher(passWord).find(),passWordBaseRuleMap.get(rule).getDesc());
            }
        }
    }
}
